package com.saceem.web.servlets;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;

import javax.ejb.EJB;
import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.saceem.imagenes.logica.ImageManager;
import com.saceem.ui.beans.FacturaBean;

/**
 * Servlet implementation class MostrarImagen
 */

@WebServlet(description = "Mostar Factura asociada al BC", urlPatterns = { "/MostrarImagen" })
public class MostrarImagen extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private final static Logger log = Logger.getLogger(MostrarImagen.class
			.getName());

	private final static String imgNa = "imagen_no_disponible.jpg";
	private final static String empresa = "010";
	private final static String imgFormat = "gif";

	@EJB
	ImageManager objManager;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public MostrarImagen() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	private void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		log.info(" ************************* Empezando proceso de mostrar imagen ***********************");
		response.setContentType("text/html;charset=UTF-8");

		String borrar = System.getProperty("reportes.web.properties");
		log.info("Property : " + borrar);

		String codigo = request.getParameter("codigo");
		String emp = request.getParameter("emp");
		// BufferedImage img = null;
		if (!codigo.isEmpty() || !emp.isEmpty()) {
			String nombre = codigo;
			String formato = nombre.substring((nombre.length() - 3));

			log.info("Codigo : " + codigo);
			log.info("Formato : " + formato);

			// ImagenesManager objManager = new ImagenesManager();

			try {
				String imgAux64 = objManager.getImage(codigo + "." + imgFormat,
						emp);

				byte[] img = objManager.getImageBlob(codigo + "." + imgFormat,
						emp);

				if (imgAux64 == null) {
					imgAux64 = objManager.getImage(imgNa, empresa);
				}

				// log.info("Descargar imagen");
				// this.test2(response, codigo, imgAux64, formato);

				// this.test(response, codigo, imgAux64, imgFormat);

				String forwardTo = "/mostrarFactura.xhtml?id=" + codigo
						+ "&factura='data:image/gif;base64," + imgAux64+"'";
				
				
//				out.print("<img alt='" + text + "' hspace=10 src='data:image/"
//						+ formato + ";base64," + base64String
//						+ "' height=800 width=800 border=1'/>");

				request.getRequestDispatcher(forwardTo).forward(request,
						response);

			} catch (Exception e) {
				log.error(e);
				e.printStackTrace();
			}
		}

		log.info(" *********************** *********************** ***********************");
	}

	/**
	 * @param fInputFile
	 * @return
	 */
	private static BufferedImage getImageTiff(File fInputFile2) {
		BufferedImage bi = null;
		ImageReadParam readParam = null;
		ImageReader rdr = null;
		Iterator<ImageReader> itr = null;
		try {
			String dirName = "C:\\borrar";
			File fInputFile = new File(dirName, "06020014126.tif");

			log.info("Existe fInputFile : " + fInputFile.exists());
			log.info("Existe fInputFile2 : " + fInputFile2.exists());

			ImageInputStream iis = ImageIO.createImageInputStream(fInputFile);

			itr = ImageIO.getImageReaders(iis);

			if (!itr.hasNext()) {
				return null;
			}

			rdr = (ImageReader) itr.next();

			rdr.setInput(ImageIO.createImageInputStream(fInputFile));
			readParam = rdr.getDefaultReadParam();
			// readParam.setSourceRegion(new Rectangle(0, 0, 300, 300));
			// if (true)
			bi = rdr.read(rdr.getMinIndex(), readParam);
			// else
			// bi = rdr.read(rdr.getMinIndex());

		} catch (IOException e) {
			log.error(e);
			e.printStackTrace();
			return null;
		}
		return bi;
	}

	private void test(HttpServletResponse response, String text,
			String base64String, String formato) {
		try {
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Mostrar Facturas</title>");
			out.println("</head>");
			// out.println("<body >");
			out.println("<body alink='#8b6029' bgcolor='#ffe9bf' vlink='#8b6029' link='#8b6029'	text='#000000'>");
			// background='img/cab_fondo.gif bgcolor='#ffe9bf' // REvisar color
			// F3AA2C
			out.println("<img src='images/logo_saceem.gif' alt='Logotipo de Saceem Sede' width='90' height='90'><br>");
			// out.println("<img src='images/logo_60.jpg' alt='Logotipo de Saceem Sede' width='90' height='90'><br>");

			out.println("<hr/>");
			out.println("<div align=center>");
			out.println("<h1 style='color:#0000FF;font-size:150%'>Mostrando factura con codigo : "
					+ text + "</h1>");

			out.print("<img alt='" + text + "' hspace=10 src='data:image/"
					+ formato + ";base64," + base64String
					+ "' height=800 width=800 border=1'/>");

			out.println("<hr/>");
			out.println("</div>");
			out.println("</body>");
			out.println("</html>");

		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	private void test2(HttpServletResponse response, String text,
			String base64String, String formato) {
		try {
			PrintWriter out = response.getWriter();
			out.println("<html>");
			out.println("<head>");
			out.println("<title>Mostrar Facturas</title>");
			out.println("</head>");
			out.println("<body>");
			out.println("<h1>Mostrar imagen con codigo : " + text + ".</h1>");

			// out.print("<img alt='' src='data:image/jpg;base64," +
			// base64String
			// + " '/>");

			out.print("<iframe width='0%' height='0' src='data:image/"
					+ formato + ";base64," + base64String + " '/>");

			out.println("</body>");
			out.println("</html>");

			// System.out.println(out.toString());
		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

}
